﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.Windows.Resources;

namespace Knihotoc_WP8.Pages
{
    public partial class ImagePage : PhoneApplicationPage
    {
        private string imagePath;

        public ImagePage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (this.NavigationContext.QueryString.ContainsKey("ImagePath"))
            {
                this.imagePath = NavigationContext.QueryString["ImagePath"];

                BitmapImage imageOnline = new BitmapImage(new Uri(this.imagePath));
                imageOnline.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(this.ImageOnline_ImageFailed);
                this.image.Source = imageOnline;
            }
        }

        private void ImageOnline_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            try
            {
                BitmapImage imageLocal = new BitmapImage();
                this.imagePath = this.imagePath.Substring(1, this.imagePath.Length - 1);
                StreamResourceInfo sr = Application.GetResourceStream(new Uri(this.imagePath, UriKind.Relative));
                imageLocal.SetSource(sr.Stream);
                this.image.Source = imageLocal;
            }
            catch (Exception)
            {
                StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/NoImage.jpg", UriKind.Relative));
                BitmapImage imageNoImage = new BitmapImage();
                imageNoImage.SetSource(sr.Stream);
                this.image.Source = imageNoImage;
            }
        }
    }
}